<template>
  <div class="dashboard">
    <v-row class="mb-4">
      <v-col cols="12">
        <h1 class="text-h4 font-weight-bold">Dashboard</h1>
        <div class="text-body-2 text-medium-emphasis">Welcome back, Admin! Here's what's happening with your store today.</div>
      </v-col>
    </v-row>

    <!-- Stats Cards -->
    <v-row class="mb-6">
      <v-col
        v-for="stat in stats"
        :key="stat.title"
        cols="12"
        md="3"
        sm="6"
      >
        <v-card
          class="stat-card border"
          :color="stat.color"
          rounded="lg"
          theme="dark"
          variant="flat"
        >
          <v-card-text class="pa-4">
            <div class="d-flex align-center justify-space-between">
              <div>
                <div class="text-subtitle-2 text-medium-emphasis">{{ stat.title }}</div>
                <div class="text-h4 font-weight-bold mt-1">{{ stat.value }}</div>
                <div class="d-flex align-center mt-2">
                  <v-icon class="mr-1" :color="stat.trend > 0 ? 'success' : 'error'" size="small">
                    {{ stat.trend > 0 ? 'mdi-arrow-up' : 'mdi-arrow-down' }}
                  </v-icon>
                  <span :class="`text-${stat.trend > 0 ? 'success' : 'error'}`">
                    {{ Math.abs(stat.trend) }}% {{ stat.trend > 0 ? 'increase' : 'decrease' }}
                  </span>
                  <span class="text-caption text-medium-emphasis ml-2">vs last month</span>
                </div>
              </div>
              <v-avatar class="elevation-3" :color="stat.color + '-darken-2'" size="56">
                <v-icon size="28">{{ stat.icon }}</v-icon>
              </v-avatar>
            </div>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>

    <!-- Charts Row -->
    <v-row class="mb-6">
      <!-- Sales Chart -->
      <v-col cols="12" md="8">
        <v-card class="h-100 border" rounded="lg" variant="flat">
          <v-card-title class="text-subtitle-1 font-weight-bold">Sales Overview</v-card-title>
          <v-card-subtitle>Last 6 months performance</v-card-subtitle>
          <v-card-text>
            <div ref="salesChart" style="height: 300px" />
          </v-card-text>
        </v-card>
      </v-col>

      <!-- Traffic Sources -->
      <v-col cols="12" md="4">
        <v-card class="h-100 border" rounded="lg" variant="flat">
          <v-card-title class="text-subtitle-1 font-weight-bold">Traffic Sources</v-card-title>
          <v-card-subtitle>Last month statistics</v-card-subtitle>
          <v-card-text>
            <div ref="trafficChart" style="height: 300px" />
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>

    <!-- Recent Orders & Activity -->
    <v-row class="mb-6">
      <!-- Recent Orders -->
      <v-col cols="12" md="8">
        <v-card class="border" rounded="lg" variant="flat">
          <v-card-title class="d-flex align-center">
            <span class="text-subtitle-1 font-weight-bold">Recent Orders</span>
            <v-spacer />
            <v-btn color="primary" size="small" variant="flat">View All</v-btn>
          </v-card-title>
          <v-card-text class="pa-0">
            <v-table class="text-caption rounded-lg" density="comfortable">
              <thead>
                <tr>
                  <th>Order ID</th>
                  <th>Customer</th>
                  <th>Date</th>
                  <th>Status</th>
                  <th class="text-right">Amount</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(order, index) in recentOrders" :key="index" class="hover-bg">
                  <td>#{{ order.id }}</td>
                  <td>{{ order.customer }}</td>
                  <td>{{ order.date }}</td>
                  <td>
                    <v-chip :color="getStatusColor(order.status)" size="small" variant="tonal">
                      {{ order.status }}
                    </v-chip>
                  </td>
                  <td class="text-right font-weight-medium">{{ order.amount }}</td>
                </tr>
              </tbody>
            </v-table>
          </v-card-text>
        </v-card>
      </v-col>

      <!-- Recent Activity -->
      <v-col cols="12" md="4">
        <v-card class="border" rounded="lg" variant="flat">
          <v-card-title class="text-subtitle-1 font-weight-bold">Recent Activity</v-card-title>
          <v-card-text class="pa-0">
            <v-timeline align="start" class="px-4 py-2" density="compact">
              <v-timeline-item
                v-for="(activity, i) in activities"
                :key="i"
                :dot-color="activity.color"
                size="small"
                width="100%"
              >
                <div class="d-flex">
                  <div class="flex-grow-1">
                    <div class="text-caption">
                      <strong class="text-body-2">{{ activity.user }}</strong> {{ activity.action }}
                    </div>
                    <div class="text-caption text-medium-emphasis mt-1">
                      <v-icon class="mr-1" size="14">mdi-clock-time-four-outline</v-icon>
                      {{ activity.time }}
                    </div>
                  </div>
                  <v-btn
                    v-if="activity.action === 'has placed a new order'"
                    color="primary"
                    icon
                    size="x-small"
                    variant="flat"
                  >
                    <v-icon size="16">mdi-arrow-right</v-icon>
                  </v-btn>
                </div>
              </v-timeline-item>
            </v-timeline>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </div>
</template>

<script setup lang="ts">
  import ApexCharts from 'apexcharts'
  import { onBeforeUnmount, onMounted, ref } from 'vue'

  // 定义图表引用
  const salesChart = ref<HTMLElement | null>(null)
  const trafficChart = ref<HTMLElement | null>(null)
  let salesChartInstance: ApexCharts | null = null
  let trafficChartInstance: ApexCharts | null = null

  // 初始化销售图表
  const initSalesChart = () => {
    if (!salesChart.value) return

    const options = {
      chart: {
        type: 'area',
        height: '100%',
        fontFamily: 'Roboto, sans-serif',
        toolbar: {
          show: true,
          tools: {
            download: true,
            selection: false,
            zoom: true,
            zoomin: true,
            zoomout: true,
            pan: false,
            reset: true,
          },
        },
      },
      colors: ['#1976d2'],
      dataLabels: {
        enabled: false,
      },
      stroke: {
        curve: 'smooth',
        width: 2,
      },
      xaxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        labels: {
          style: {
            colors: '#6e6e6e',
          },
        },
        axisBorder: {
          show: true,
          color: '#e0e0e0',
        },
        axisTicks: {
          show: true,
          color: '#e0e0e0',
        },
      },
      yaxis: {
        title: {
          text: 'Sales ($)',
          style: {
            color: '#6e6e6e',
          },
        },
        labels: {
          style: {
            colors: '#6e6e6e',
          },
          formatter: (value: number) => `$${value}`,
        },
      },
      tooltip: {
        y: {
          formatter: (value: number) => `$${value}`,
        },
      },
      grid: {
        borderColor: '#e0e0e0',
        strokeDashArray: 4,
      },
      fill: {
        type: 'gradient',
        gradient: {
          shadeIntensity: 1,
          opacityFrom: 0.7,
          opacityTo: 0.3,
        },
      },
    }

    const series = [{
      name: 'Sales',
      data: [30_000, 40_000, 35_000, 50_000, 49_000, 60_000],
    }]

    salesChartInstance = new ApexCharts(salesChart.value, {
      ...options,
      series,
    })
    salesChartInstance.render()
  }

  // 初始化流量来源图表
  const initTrafficChart = () => {
    if (!trafficChart.value) return

    const options = {
      chart: {
        type: 'donut',
        height: '100%',
        fontFamily: 'Roboto, sans-serif',
      },
      colors: ['#1976d2', '#26a69a', '#ffa726', '#ef5350', '#ab47bc'],
      labels: ['Direct', 'Organic', 'Referral', 'Social', 'Email'],
      legend: {
        position: 'bottom',
        labels: {
          colors: '#6e6e6e',
        },
      },
      plotOptions: {
        pie: {
          donut: {
            size: '65%',
            labels: {
              show: true,
              total: {
                show: true,
                label: 'Total',
                color: '#6e6e6e',
                formatter: () => '100%',
              },
            },
          },
        },
      },
      dataLabels: {
        enabled: false,
      },
      tooltip: {
        y: {
          formatter: (value: number) => `${value}%`,
        },
      },
    }

    const series = [44, 55, 13, 43, 22]

    trafficChartInstance = new ApexCharts(trafficChart.value, {
      ...options,
      series,
    })
    trafficChartInstance.render()
  }

  // 组件挂载时初始化图表
  onMounted(() => {
    initSalesChart()
    initTrafficChart()
  })

  // 组件卸载前销毁图表实例
  onBeforeUnmount(() => {
    if (salesChartInstance) {
      salesChartInstance.destroy()
    }
    if (trafficChartInstance) {
      trafficChartInstance.destroy()
    }
  })

  // 定义统计卡片数据类型
  interface StatItem {
    title: string
    value: string
    progress: number
    color: string
    trend: number
    icon: string
  }

  // 定义活动记录类型
  interface Activity {
    user: string
    action: string
    time: string
    color: string
  }

  // 定义订单类型
  interface Order {
    id: string
    customer: string
    date: string
    status: 'Completed' | 'Processing' | 'Shipped' | 'Pending' | 'Cancelled'
    amount: string
  }

  // 统计卡片数据
  const stats: StatItem[] = [
    {
      title: 'Total Users',
      value: '2,345',
      progress: 75,
      color: 'primary',
      trend: 12.5,
      icon: 'mdi-account-group',
    },
    {
      title: 'Revenue',
      value: '$34,543',
      progress: 50,
      color: 'success',
      trend: 8.3,
      icon: 'mdi-currency-usd',
    },
    {
      title: 'Pending Orders',
      value: '45',
      progress: 25,
      color: 'warning',
      trend: -5.2,
      icon: 'mdi-cart-outline',
    },
    {
      title: 'Bounce Rate',
      value: '12.5%',
      progress: 12.5,
      color: 'error',
      trend: -2.1,
      icon: 'mdi-chart-line',
    },
  ]

  // 活动记录数据
  const activities: Activity[] = [
    {
      user: 'John Doe',
      action: 'has placed a new order',
      time: '2 minutes ago',
      color: 'primary',
    },
    {
      user: 'Jane Smith',
      action: 'updated the dashboard',
      time: '1 hour ago',
      color: 'success',
    },
    {
      user: 'Mike Johnson',
      action: 'has placed a new order',
      time: '3 hours ago',
      color: 'info',
    },
    {
      user: 'Sarah Williams',
      action: 'created a new report',
      time: '5 hours ago',
      color: 'warning',
    },
  ]

  // 最近订单数据
  const recentOrders: Order[] = [
    {
      id: 'ORD-001',
      customer: 'John Smith',
      date: '2023-05-15',
      status: 'Completed',
      amount: '$125.00',
    },
    {
      id: 'ORD-002',
      customer: 'Emma Johnson',
      date: '2023-05-14',
      status: 'Processing',
      amount: '$89.99',
    },
    {
      id: 'ORD-003',
      customer: 'Michael Brown',
      date: '2023-05-14',
      status: 'Shipped',
      amount: '$234.50',
    },
    {
      id: 'ORD-004',
      customer: 'Sarah Davis',
      date: '2023-05-13',
      status: 'Pending',
      amount: '$56.75',
    },
    {
      id: 'ORD-005',
      customer: 'David Wilson',
      date: '2023-05-13',
      status: 'Completed',
      amount: '$178.30',
    },
  ]

  // 获取状态对应的颜色
  const getStatusColor = (status: Order['status']): string => {
    const statusColors = {
      Completed: 'success',
      Processing: 'info',
      Shipped: 'primary',
      Pending: 'warning',
      Cancelled: 'error',
    } as const

    return statusColors[status] || 'secondary'
  }
</script>

<style scoped>
.h-100 {
  height: 100%;
}
</style>
